<template>
  <div style="margin: 50px">
    <t-row class="rows">
      <t-col :span="1">
        <span>手动更新用户凭据</span>
      </t-col>
      <t-col :span="2" class="rightCols">
        <div style="float: right">
          <InfoCircleFilledIcon style="color: indianred;" size="small"/>
          <span style="font-size: 0.8em; color: indianred">在数据无法自动更新时请执行此项</span>
          <t-button style="margin-left: 10px" @click="reLogin">执行</t-button>
        </div>
      </t-col>
    </t-row>
    <t-row class="rows">
      <t-col :span="1">
        <span>自动更新数据类型</span>
      </t-col>
      <t-col :span="2" class="rightCols">
        <t-radio-group variant="outline" :value="dataUseOption" @change="dataUseOptionChange($event)">
          <t-radio-button value="fact">实际数据</t-radio-button>
          <t-radio-button value="demo">示例数据</t-radio-button>
        </t-radio-group>
      </t-col>
    </t-row>
    <t-row class="rows">
      <t-col :span="1">
        <span>新增示例数据</span>
      </t-col>
      <t-col :span="2" class="rightCols">
          <div style="float: right">
            <t-dropdown :options="deviceOptions" @click="deviceOptionChange" maxColumnWidth="200">
              <t-button variant="text">
                {{ deviceSelected.selection.content }}
                <template #suffix> <t-icon name="chevron-down" size="16" /></template>
              </t-button>
            </t-dropdown>
            <t-button style="margin-left: 10px" @click="generateDemoData">执行</t-button>
          </div>
      </t-col>
    </t-row>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref} from "vue";
import axios from "axios";
import config from "../assets/config.json";
import {useStore} from "vuex";
import {DropdownOption, MessagePlugin} from "tdesign-vue-next";
import {AddCircleIcon, ErrorCircleFilledIcon, InfoCircleFilledIcon} from "tdesign-icons-vue-next";

const store = useStore();
const devicesStored = computed(() => store.getters["Devices/getDevices"]);
const dataUseOption = ref("fact");
const deviceOptions: Array<DropdownOption> = [];
const deviceSelected = reactive({ selection: { content: "选择设备", value: ""} });


onMounted(() => {
  getPeriUpdateUse().then(what => {
    dataUseOption.value = what;
  });

  for (let i = 0; i < devicesStored.value.length; i++) {
    deviceOptions.push({
      content: devicesStored.value[i].name,
      value: devicesStored.value[i].device_number
    });
  }
  console.log(deviceOptions.length);
});

const reLogin = () => {
  axios({
    baseURL: `http://${config.host}:${config.port}`,
    url: `${config.apiPrefix}/${config.apiSuffix.periUpdateUse}`,
    method: "GET"
  }).then(() => {
    getPeriUpdateUse().then(what => {
      dataUseOption.value = what;
      MessagePlugin.success({ content: "设置成功", closeBtn: true});
    });
  }).catch(err => {
    MessagePlugin.error({ content: "设置失败", closeBtn: true});
  });
}

const dataUseOptionChange = (e: any) => {
  dataUseOption.value = e
  let url = "";
  if (dataUseOption.value == "fact") {
    url = `${config.apiPrefix}/${config.apiSuffix.useFactData}`
  } else if (dataUseOption.value == "demo") {
    url = `${config.apiPrefix}/${config.apiSuffix.useDemoData}`
  }
  axios({
    baseURL: `http://${config.host}:${config.port}`,
    url: url,
    method: "GET"
  }).then(() => {
    getPeriUpdateUse().then(what => {
      dataUseOption.value = what;
      MessagePlugin.success({ content: "设置成功", closeBtn: true});
    });
  }).catch(err => {
    MessagePlugin.error({ content: "设置失败", closeBtn: true});
  });
}

const deviceOptionChange = (e: any) => {
  deviceSelected.selection = e
}

function getPeriUpdateUse() : Promise<string> {
  return new Promise<string>((resolve, reject) => {
    axios({
      baseURL: `http://${config.host}:${config.port}`,
      url: `${config.apiPrefix}/${config.apiSuffix.periUpdateUse}`,
      method: "GET"
    }).then(response => {
      if (response.status === 200 && response.data.status === "success") {
        resolve(response.data['use']);
      } else {
        throw Error("status is not success.");
      }
    }).catch(err => {
      MessagePlugin.error({ content: "网络请求失败", closeBtn: true});
      reject(err);
    });
  });
}

function generateDemoData() {
  axios({
    baseURL: `http://${config.host}:${config.port}`,
    url: `${config.apiPrefix}/${deviceSelected.selection.value}/${config.apiSuffix.generateDemoData}`,
    method: "GET"
  }).then(response => {
    if (response.status === 200 && response.data.status === "success") {
      MessagePlugin.success({content: "成功新增一条示例数据", closeBtn: true});
    } else {
      MessagePlugin.error({content: "新增失败", closeBtn: true});
      throw Error("status is not success.");
    }
  }).catch(err => {
    MessagePlugin.error({content: "新增失败", closeBtn: true});
    console.log(err)
  });
}
</script>

<style scoped>
.rows {
  margin-block: 10px;
}

.rightCols {
  text-align: right;
}
</style>